package fr.liglab.adele.icasa.impl;

import org.apache.felix.ipojo.annotations.Component;
import org.apache.felix.ipojo.annotations.Invalidate;
import org.apache.felix.ipojo.annotations.Provides;
import org.apache.felix.ipojo.annotations.Requires;
import org.apache.felix.ipojo.annotations.Validate;

import fr.liglab.adele.icasa.EcoLighting;
import fr.liglab.adele.icasa.device.DeviceListener;
import fr.liglab.adele.icasa.device.light.BinaryLight;
import fr.liglab.adele.icasa.device.presence.PresenceSensor;
import fr.liglab.adele.icasa.environment.SimulatedEnvironment;
import fr.liglab.adele.icasa.environment.SimulatedEnvironmentManager;

@Component
@Provides
public class EcoLightingImpl implements Runnable, EcoLighting, DeviceListener {

	@Requires
	BinaryLight light;
	
	@Requires
	PresenceSensor sensor;
	
	@Requires
	SimulatedEnvironmentManager manager;
	
	@Requires
	SimulatedEnvironment environment;
	
	Thread runner;
	
	int hits=0;
	
	public void run(){
	
		light.setPowerStatus(true);
		
		System.out.println("<Light ON/>");
		
		while(hits-->0){
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	
		System.out.println("<Light OFF/>");
		
		light.setPowerStatus(false);
		
		runner=null;
		
	}
	
	@Validate
	public void starting() {
		
		manager.bindDeviceToEnvironment("nameLight", "enclosedEnvironment");
		manager.bindDeviceToEnvironment("nameSensor", "enclosedEnvironment");
		
		environment.setProperty(SimulatedEnvironment.VOLUME, 2.0d);
		environment.setProperty(SimulatedEnvironment.TEMPERATURE, 0.1d);
		environment.setProperty(SimulatedEnvironment.ILLUMINANCE, 1d);
		environment.setProperty(SimulatedEnvironment.PRESENCE, 1d);

		sensor.addListener(this);
		
	}
	
	@Invalidate
	public void stopping() {
		//DO ME
		
	}

	public void notifyDeviceEvent() {
		hits=1;
		
		if(runner==null){
			runner=new Thread(this);
			runner.start();
		}
	}
	
}
